package v1

import (
	"fmt"
	"gin-project/model"
	"gin-project/utils/errmsg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

func InsertSinger(ctx *gin.Context) {
	username := ctx.PostForm("name")
	sexStr := ctx.PostForm("sex")
	sex, _ := strconv.Atoi(sexStr)
	birth := ctx.PostForm("birth")
	location := ctx.PostForm("location")
	introduction := ctx.PostForm("introduction")

	fmt.Println(username)
	fmt.Println(sexStr)
	fmt.Println(birth)
	fmt.Println(location)
	fmt.Println(introduction)

	var singer model.Singer
	singer.Name = username
	singer.Sex = sex
	singer.Birth = birth
	singer.Location = location
	singer.Introduction = introduction

	code := model.InsertSinger(&singer)
	if code != errmsg.SUCCESS {
		ctx.JSON(http.StatusOK, gin.H{
			"code": code,
			"msg": errmsg.GetErrMsg(code),
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg": errmsg.GetErrMsg(200),
	})
	return
}

func SelectSingers(ctx *gin.Context) {
	singers, code := model.SelectSingers()
	if code != errmsg.SUCCESS {
		ctx.JSON(http.StatusOK, gin.H{
			"code" : code,
			"msg" : errmsg.GetErrMsg(code),
			"data": nil,
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code" : code,
		"msg" : errmsg.GetErrMsg(code),
		"data": singers,
	})
	return
}

func UpdateSingerPic(ctx *gin.Context) {
	file, header, err := ctx.Request.FormFile("file")
	id := ctx.PostForm("id")

	if err != nil {
		fmt.Println("获取图片失败。。。")
		ctx.JSON(http.StatusOK, gin.H{
			"code": errmsg.ERROR,
			"msg" : errmsg.GetErrMsg(errmsg.ERROR),
		})
		return
	}

	url, code := model.UpdateSingerPic(file, header)
	if code != errmsg.SUCCESS {
		ctx.JSON(http.StatusOK, gin.H{
			"code": code,
			"msg" : errmsg.GetErrMsg(code),
		})
		return
	}

	code = model.UpdateSinger(map[string]interface{}{
		"pic": url,
	}, id)
	ctx.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg" : errmsg.GetErrMsg(code),
	})
	return
}

func UpdateSinger(ctx *gin.Context) {
	id := ctx.PostForm("id")
	name := ctx.PostForm("name")
	sex := ctx.PostForm("sex")
	birth := ctx.PostForm("birth")
	location := ctx.PostForm("location")
	introduction := ctx.PostForm("introduction")

	code := model.UpdateSinger(map[string]interface{}{
		"name":         name,
		"sex":          sex,
		"birth":        birth,
		"location":     location,
		"introduction": introduction,
	}, id)

	ctx.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": errmsg.GetErrMsg(code),
	})
	return
}

func DeleteSinger(ctx *gin.Context) {
	id := ctx.Query("id")
	code := model.DeleteSinger(id)
	if code != errmsg.SUCCESS {
		ctx.JSON(http.StatusOK, gin.H{
			"code": code,
			"msg": errmsg.GetErrMsg(code),
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": errmsg.GetErrMsg(code),
	})
	return
}